<template>
	<view class="form-content">
		<up-form labelWidth="0" :model="formData" :rules="rules" ref="formRef">
			<up-form-item prop="phone" borderBottom>
				<up-input placeholder="请输入手机号" v-model="formData.phone" border="none"></up-input>
			</up-form-item>
			<up-form-item prop="code" borderBottom>
				<up-input border="none" placeholder="请输入验证码" v-model="formData.code">
					<template #suffix>
						<up-code ref="uCodeRef" @change="codeChange" seconds="20" changeText="X秒重新获取"></up-code>
					<!-- 	<up-button @tap="getCode" :text="tips" type="success" size="mini"></up-button> -->
						<text @tap="getCode">{{tips}}</text>
					</template>
				</up-input>
			</up-form-item>
		</up-form>
		<up-button @click="doLogin">登录</up-button>
	</view>
</template>

<script setup>
	import {
		ref
	} from 'vue';
import { GET_CODE, DO_LOGIN } from '../../api/codeLogin';
import { debounce } from 'uview-plus';

	const formData = ref({
		phone: '',
		code: ''
	})
	const rules = ref({
		phone: {
			type: 'string',
			required: true,
			message: '请输入手机号',
			trigger: ['blur', 'change']
		},
		code: {
			type: 'string',
			required: true,
			message: '请输入验证码',
			trigger: ['blur', 'change']
		}
	})
	const formRef = ref(null)
	const uCodeRef = ref(null)
	const tips = ref('')
	const codeChange = (text) => {
	  tips.value = text;
	};
	// 可以从组件库里面粘贴过来，但是要改，有错误代码
	const getCode = () => {
		if(!formData.value.phone) {
			uni.$u.toast('请输入手机号')
			return
		}
		// 判断当前是否正在倒计时
	  if (uCodeRef.value.canGetCode) {
	    // 模拟向后端请求验证码
	    uni.showLoading({
	      title: '正在获取验证码',
	    });
		GET_CODE().then(res => {
			console.log(res)
			uni.hideLoading();
			uni.$u.toast('验证码已发送');
			uCodeRef.value.start();
			uni.setStorageSync('code', res.code)
		})
	  } else {
	    uni.$u.toast('倒计时结束后再发送');
	  }
	};
	const doLogin = () => debounce(() => {
		uni.$u.toast('请稍后重试')
		formRef.value.validate().then(valid => {
			console.log(valid)
			if(valid) {
				console.log(formData.value.code)
				const code = uni.getStorageSync('code')
				if(code === formData.value.code) {
					DO_LOGIN(formData.value.phone).then(res => {
						console.log(res)
						uni.setStorageSync('phone', res.phone)
						uni.setStorageSync('token', res.token.token)
						uni.navigateTo({
							url: '/pages/index/index'
						})
					})
				} else {
					uni.$u.toast('验证码输入错误');
				}
			}
		})
	}, 500)       
</script>

<style lang="scss" scoped>
	.form-content {
		padding: 0 30rpx;
		margin-top: 30rpx;
	}
</style>